<template>
	<view class="login-container" :class="[themeType]">

		<image  :src="bgImg" mode="aspectFill" class="image-bg" :class="[APP_TYPE]"></image>

		<view class="mask" :class="[APP_TYPE]">
			<view class="login-img" >
				<image :src="icon" class="image-logo"></image>
			</view>
			<view class="welcome">
				<view>您好，</view>
				<view>欢迎来到商城服务</view>
			</view>
			<view class="btns">
				<button :open-type="read ? 'getPhoneNumber' : ''" @click="toAgree" @getphonenumber="getPhoneNumber"
					class="form-btn">微信用户一键登录</button>
				<button class="form-btn phone-btn" @click="toLoginByPhone">手机号登录</button>
				<user-agree-fy :read.sync="read" />
			</view>
		</view>
		<u-modal :show="showRead" :showConfirmButton="false" >
			<view class="modal-sty">
				<view class="close" @tap="showRead = false">
					<u-icon name="close" color="#1e2124" size="10"></u-icon>
				</view>
				<view class="content">
					<text class="wficon-tishi-01 iconfont"></text>请勾选同意用户服务协议内容。
				</view>
				<view class="footer">
					<view class="btn-wrapper">
						<view class="btn confirm-btn" @tap="showRead = false">确定</view>
					</view>
				</view>
			</view>
		</u-modal>
		<!-- 多账号 -->
	</view>
</template>

<script>
	import userAgree from '@/pages/user/components/user-agree/user-agree.vue';
	import userAgreeFy from '@/pages/user/components/user-agree-fy/user-agree-fy.vue';
	import {
		mapMutations,
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				bgImg: require(`@/pages/user/static/${process.env.VUE_APP_TYPE}-bg.png`),
				read: false,
				showRead: false,

				/** 多账号 */
				showAccoSel: false,
				oldDataModel: null, // 登录参数 (上次的)
				multAccoList: [],
				imagePrefix: process.env.VUE_APP_TYPE !== 'MALL' ? 'http://v5demo.sh-fengze.com:19080' : 'https://www.fengze.cloud',
				open_code: '',
			}
		},
		components: {
			userAgree,
			userAgreeFy
		},
		computed: {
			...mapState(['userImage', 'nickName', 'userInfo', 'perviewPageUrl', 'themeType']),
			APP_TYPE() {
				return process.env.VUE_APP_TYPE
			},
			icon() {
				let iconName = process.env.VUE_APP_TYPE !== 'MALL' ? `${this.themeType}.svg` : `${process.env.VUE_APP_TYPE}-icon-new.svg`
				return require(`@/pages/user/static/${iconName}`)
			}
		},
		onLoad(option) {
			uni.login({
				success: res => {
					this.open_code = res.code
				}
			})
		},
		methods: {
			...mapMutations(['setUserPhone', 'setUserId', 'setAccessToken', 'setAccessTokenTime', 'setRefreshTokenTime',
				'setRefreshToken', 'removeUserImage', 'removeNickName', 'setCurrentUserInfo', 'removePerviewPageUrl', 'setIsAdmin',
				'setThemeType', 'setCheckRoleId'
			]),
			toAgree() {
				if (this.read) return
				this.showRead = true
			},
			toLoginByPhone() {
				uni.navigateTo({
					url: '/user-pages/UserLayout/LoginPhone/LoginPhone'
				})
			},
			/** 微信授权手机号登录 */
			getPhoneNumber(e) {
				var _this = this;
				// 如果用户不同意授权则返回并结束
				if (e.detail.errMsg !== "getPhoneNumber:ok") {
					return;
				}
				//登录接口失败
				if (!this.open_code) return
				let dataModel = {
					userImage: this.userImage,
					nickName: this.nickName,
					headimgurl: this.userImage,
					iv: e.detail.iv,
					encryptedData: e.detail.encryptedData,
					phone_code: e.detail.code,
					mall_id: process.env[`VUE_APP_${process.env.VUE_APP_TYPE}_ID`],
					headimgurl: this.userImage,
					system_type: process.env[`VUE_APP_${process.env.VUE_APP_TYPE}_SYSTEM_TYPE`],
					open_code: this.open_code,
					gender: this.userInfo.gender,
					city: this.userInfo.city,
					province: this.userInfo.province,
					country: this.userInfo.country
				};
				this.loginApi(dataModel)
				//为兼容旧基础库，已在onLoad调用。
				// uni.login({
				// 	success(res) {
				// 		if (!res.code) return
				// 		dataModel.open_code = res.code;
				// 		// 调用登录接口
				// 		_this.loginApi(dataModel)
				// 	}
				// })
			},
			/** 已经拿到手机号跟login code, 调用登录接口 */
			loginApi(dataModel) {
				uni.showLoading({
					title: '正在登录'
				});
				this.$u.api.loginApi(dataModel)
				.then(async response => {
					uni.hideLoading();
					if (response.data.success) {
						// 登录成功, 调用其他接口 获取用户的个人信息
						this.successLogin(response)
					} else if (response.data.errorcode === '99999' && process.env.VUE_APP_TYPE === 'MALL') {
						// 云小程序: 登录失败, 多账号登录 先选要登录哪个账号
						this.multAccoSel(dataModel, response.data)
					} else if (response.data.errorcode === '40163') {
						uni.showToast({
							title: '授权已过期,请重新授权',
							icon: 'none',
							duration: 3000,
							mask: true
						})
						setTimeout(_ => {
							uni.navigateBack({ delta: 2 });
						}, 3000)
					} else {
						uni.showToast({
							title: response.data.msg,
							icon: 'none',
							duration: 2000,
							mask: true
						})
					}
				}).catch(err => {
					uni.hideLoading();
					uni.showToast({
						title: err.errMsg,
						icon: 'none',
						duration: 2000,
						mask: true
					})
				})
			},
			/** 云小程序: 多账号登录, 弹出账号选择框 */
			multAccoSel(dataModel, res) {
				/** 
				 * res.data: Array<{
				 * 	company_name: "酆泽有限公司",
				 * 	login_sign: "9722aa3fd3f44876b5dd9e2c5009bc04WUI0000000000000029"
				 * }> 
				 */
				this.showAccoSel = true
				this.oldDataModel = dataModel

				const multAccoList = JSON.parse(JSON.stringify(res.data))
				this.multAccoList = multAccoList
			},
			/** 云小程序: 确定选择的账号, 关闭弹框 */
			confirmAcco(acco) {
				if(!acco) return
				this.oldDataModel.login_sign = acco.login_sign
				this.loginApi(this.oldDataModel)
				this.showAccoSel = false
			},
			
			async successLogin(response) {
				this.setAccessToken(response.data.data.access_token)
				this.setAccessTokenTime(response.data.data.time)
				this.setRefreshToken(response.data.data.refresh_token)
				this.setRefreshTokenTime(response.data.data.refresh_token_time)
				this.setUserPhone(response.data.data.phone)
				this.setUserId(response.data.data.user_id)
				// 获取用户信息
				const res = await this.$u.api.getCurrUser();
				if (res?.data?.success && res?.data?.data) {
					this.setCurrentUserInfo(res.data.data);
					// 设置主题
					this.setThemeType(res.data?.data?.themeType);
					this.setCheckRoleId(res.data.data.defaultRole)
					if (process.env.VUE_APP_TYPE !== 'TENANT') {
						const { data: isAdmin } = await this.$u.api.isshow({
							roleId: res.data.data.defaultRole || '',
						})
						this.setIsAdmin(isAdmin.data);
					}
				}
				const token = uni.getStorageSync('accessToken');
				if (!token) {
					return;
				}
				if (this.perviewPageUrl) {
					uni.reLaunch({
						url: "/" + this.perviewPageUrl
					});
					// 移除预览页面
					this.removePerviewPageUrl();
				} else {
					if (process.env.VUE_APP_TYPE === 'MALL') {
						uni.redirectTo({
							url: '/one-level-pages/index/index'
						})
						return
					}
					// #ifdef MP-WEIXIN
					const updateManager = uni.getUpdateManager()
					updateManager.onUpdateReady(() => {
						uni.showModal({
							title: '更新提示',
							content: '新版本已经准备好，是否重启应用？',
							success: (res) => {
								if (res.confirm) {
									// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
									updateManager.applyUpdate()
								}
							}
						})
					})
					// #endif
				}
			}
		}
	}
</script>
<style scoped lang="scss">
	.login-container {
		position: relative;
		width: 100%;
		height: 100%;
		overflow-x: hidden;

		.image-bg {
			width: 100vw;
			height: 100vh;
			position: absolute;
			&.MALL {
				width: 584rpx;
				height: 496rpx;
				left: 236rpx;
				top: 0;
				z-index: 1;
			}
		}
		


		.mask {
			position: relative;
			background: rgba(255, 255, 255, 0.3);
			&.MALL {
				width: 100%;
				height: 100%;
				.login-img {
					top: 212rpx;
				}
				.btns {
					width: 686rpx;
					top: 584rpx;
				}
			}
			&.MALL {
				width: 100%;
				height: 100%;
				background: rgba(255, 255, 255, 1);
				.welcome {
					position: absolute;
					z-index: 2;
					left: 52rpx;
					top: 272rpx;
					font-size: 40rpx;
					font-family: PingFangSC-Semibold, PingFang SC;
					font-weight: 600;
					color: var(--c-emphasize-primary-color);
					line-height: 56rpx;
					// background: var(--c-primary-color);
					// background-clip: text;
  				// -webkit-text-fill-color: transparent;
				}
				.login-img {
					top: 120rpx;
					left: 52rpx;
					width: 128rpx;
					height: 128rpx;
					transform: translate(0);
					// background: var(--c-primary-color);
					background: var(--c-emphasize-primary-color);
				}

				.btns {
					width: 648rpx;
					min-height: 274rpx;
					top: 544rpx;
					justify-content: flex-start;
					.form-btn {
						width: 100%;
						height: 88rpx;
						line-height: 88rpx;
						background: var(--c-emphasize-primary-color);
						box-shadow: 0px 8rpx 16rpx 0px rgba(52,118,255,0.3);
						border-radius: 44rpx;
						opacity: 1;
						font-size: 16px;
						color: #fff;
						margin-bottom: 40rpx;
						// background: var(--c-primary-color);

						&::after{
							border: none;
						}

						&.phone-btn {
							margin-bottom: 24rpx;
							background: #EAECFE;
							color: var(--c-emphasize-primary-color);
							box-shadow: none;
							border: none;
						}
					}
				}
			}
			&.TENANT {
				left: 50%;
				transform: translate(-50%);
				top: 108rpx;
				width: 686rpx;
				height: 800rpx;
				.login-img {
					top: 98rpx;
					background: #fff;
				}
				.btns {
					width: 622rpx;
					top: 470rpx;
				}
			}

			.login-img {
				left: 50%;
				transform: translate(-50%);
				position: absolute;
				width: 160rpx;
				height: 160rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 16rpx;
				overflow: hidden;

				.image-logo {
					width: 100%;
					height: 100%;
				}
			}

			.btns {
				margin: 0 auto;
				position: relative;
				height: 224rpx;
				display: flex;
				justify-content: space-between;
				flex-direction: column;

				.form-btn {
					width: 100%;
					height: 96rpx;
					background: var(--c-primary-color);
					border-radius: 64rpx 64rpx 64rpx 64rpx;
					opacity: 1;
					font-size: 18px;
					font-weight: 500;
					color: #fff;

					&.phone-btn {
						background: transparent;
						border: 1px solid var(--c-emphasize-primary-color);
						color: var(--c-emphasize-primary-color);
					}
				}
			}
		}

		.modal-sty{
			@include flex(flex-start, column);
			align-items: flex-start;
			width: 100%;
			background-color: #ffffff;
			padding: 30rpx;
			.close {
				position: absolute;
				right: 28rpx;
				top: 28rpx;
				border-radius: 50%;
				background-color: #f8f8f8;
				padding: 20rpx;
				box-sizing: border-box;
				height: 46rpx;
				width: 46rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
			.content{
				margin-top: 32rpx;
				font-size: 26rpx;
				font-weight: 400;
				color: #000000;
				width: 100%;
				box-sizing: border-box;
				display: flex;
				align-items: center;
				.iconfont {
					color: var(--c-emphasize-primary-color);
					margin-right: 10rpx;
				}
			}
			.footer{
				width: 100%;
				margin-top: 84rpx;
				@include flex(center);
				.btn-wrapper{
					@include flex(center);
					width: 50%;
					.btn{
						width: 160rpx;
						border-radius: 8rpx;
						@include flex(center);
						flex: 1;
						height: 40px;

					}
					.confirm-btn{
						background: var(--c-primary-color);
						color: #FFFFFF;
					}
					
				}
			}
		}

		
		
		::v-deep .u-popup:last-child .u-modal__content {
			background-color: transparent;
			background: transparent;
			padding: 0;
			padding-top: 0 !important;
			position: relative;
		}
		::v-deep .u-popup:last-child {
			background: transparent;
		}
		::v-deep .u-popup:last-child .u-popup__content{
			background-color: rgba(255,255,255, 0.4);
		}
	}
	
</style>
